import {ChangeDetectorRef, Component, ViewChild} from '@angular/core';
import {IonicPage, LoadingController, NavController, NavParams, Platform, ToastController} from 'ionic-angular';
import {DomSanitizer, SafeResourceUrl} from '@angular/platform-browser';
import moment from 'moment';
import {FileService} from "../../../../services/native/file/file.service";
import {LocalStorageService} from "../../../../services/native/local-storage/local-storage.service";
import {FileOpener} from "@ionic-native/file-opener";
import {FileTransfer} from "@ionic-native/file-transfer";
import {WechatService} from "../../../../services/native/wechat/wechat.service";
import {ActivityDetailProvider} from "../../../../providers/activity/activity-detail/activity-detail.provider";
import {ActivityListItemModel} from "../../../../model/pages/activity/activity-list/activity-list-item.model";
import {ActivityListProvider} from "../../../../providers/activity/activity-list/activity-list.provider";
import {RosterListComponent} from "../../../../components/pages/activity/activity-detail/roster-list.component";
import {LoadingService} from "../../../../services/common/loading.service";
import {Role, RoleFactory} from "../../../../services/common/role.service";
import {AuthService} from "../../../../services/common/auth.service";
import $ from 'jquery';
import {ThemeBrowserService} from "../../../../services/native/theme-browser/theme-browser.service";
import {PermissionsService} from "../../../../services/native/permissions/permissions.service";
import {CacheImgService} from "../../../../services/native/cache-img/cache-img.service";

declare let Wechat;

/**
 * 活动详情
 */
@IonicPage()
@Component({
    selector: 'page-activit-detail',
    templateUrl: 'activit-detail.html',
    providers: [
        FileOpener, FileService, LocalStorageService, FileTransfer,
        WechatService, ActivityDetailProvider, ActivityListProvider,
        ThemeBrowserService,
        AuthService,PermissionsService
    ]
})
export class ActivitDetailPage {

    @ViewChild(RosterListComponent) rosterListCom: RosterListComponent;

    showShareMenu: boolean;
    private activityId;
    detailData: ActivityListItemModel = new ActivityListItemModel();
    officialDocs: any;
    trainDocs: any;
    toolsDocs: any;
    allTypes = [];
    classify: any;

    shareUrl:SafeResourceUrl;
    // 原链接
    shareLink: any;
    showShareButton = false;
    unixResolve = moment.unix;
    showRoster;

    _tabActivity: string = 'detail';
    public get activity(): string {
        return this._tabActivity;
    }
    public set activity(v: string) {
        this._tabActivity = v;
        if (v === 'joinCust') {
            // this.rosterListCom.subscribeEvents();
            // this.rosterListCom.getRosterList();
        } else {
            // this.rosterListCom.unSubscribeEvents();
        }
    }
    prevActivity;
    constructor(public navCtrl: NavController, public navParams: NavParams,
                public loadingCtrl: LoadingController,
                private sanitizer: DomSanitizer,
                private fileService: FileService,
                public wechatService: WechatService,
                private fileOpener: FileOpener,
                private activityDetailPro: ActivityDetailProvider,
                private activityListPro: ActivityListProvider,
                public themeBrowserService: ThemeBrowserService,
                private load: LoadingService,
                private toast: ToastController,
                private ref: ChangeDetectorRef,
                private permissionsService: PermissionsService,
                private platform: Platform,
                private authService: AuthService,
                private cacheImg: CacheImgService) {
        this.activityId = this.navParams.get('id');
        this.classify = this.navParams.get('classify');
        this.prevActivity = this.activity;
    }

    /**
     * toast提示
     * @param {string} msg
     * @param {number} duration
     */
    showToast(msg: string,duration = 1200) {
        this.toast.create({
            message: msg,
            position: 'middle',
            duration: duration,
            dismissOnPageChange:true
            // ,
            // showCloseButton:true,
            // closeButtonText:"关闭"
        }).present();
    }
    ionViewDidLoad() {
        this.getActivityType();
        this.getActivityDetail();
        this.showRoster = this.authService.showRoster();
        this.contentClickHandle();
    }
    //内勤人员分享链接
    backOfficeShare(){
        this.shareLink = this.detailData.shareLink;
        this.shareUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.shareLink);
        this.showShareButton = true;
    }

    roleIsAllowShare = false;

    //营销员分享链接
    getWechatBindState(){
        this.activityDetailPro.getActivityShare(this.detailData.id).subscribe(data => {
            let result:any = data;
            this.roleIsAllowShare = result.openWebChat;
            if(result && result.openWebChat){
                this.shareLink = result.shareUrl;
                this.shareUrl = this.sanitizer.bypassSecurityTrustResourceUrl(result.shareUrl);
                this.showShareButton = true;
            }
        });
    }

    /**
     * 是否可以分享到微信
     */
    weChatShare(){
        if(this.roleIsAllowShare){
            this.showShareMenu = true;
        }else{
            this.showShareMenu = false;
            this.showToast('请先至中宏保险官微完成身份绑定,再进行活动转发。')
        }

    }
    /**
     * 获取活动详情
     */
    getActivityDetail() {
        this.load.showLoading();
        this.activityDetailPro.getActivityDetailById(this.activityId, 0)
            .subscribe((res: ActivityListItemModel) => {
                this.detailData = res;
                if (this.detailData) {
                    this.officialDocs = this.detailData.officialDocs;
                    this.trainDocs = this.detailData.trainDocs;
                    this.toolsDocs = this.detailData.toolsDocs;
                    this.completionUrl([this.detailData.bannerUrl, this.detailData.shareImgUrl])
                        .then((urlArr) => {
                            this.detailData.bannerLink = urlArr[0];
                            this.detailData.shareImgLink = urlArr[1];
                        });
                    const userRole = RoleFactory.getUserRole();
                    if(userRole == Role.营销员){
                        this.getWechatBindState();
                    }else{
                        this.backOfficeShare();
                    }
                }
                this.load.dismissLoading();
                this.contentHyperlinkHandle();
            }, err => {
                this.load.dismissLoading();
            });
    }

    // 内容超链接处理
    contentHyperlinkHandle(){
        setTimeout(() => {

            const aTargets = $('.segDetail').find('a');
            aTargets.each(function(){
                const hyperLink = $(this).attr('href');
                $(this).attr('href','javascript:void 0');
                $(this).attr('data-link',hyperLink);
            });

        },500);
    }

    contentClickHandle(){
        const _self = this;
        // $('.segDetail').click(function(e){
        $('.actIntro').click(function(e){
            if(e.target.nodeName === 'A'){
                e.preventDefault();
                const url = $(e.target).attr('data-link');
                if(url){
                    _self.themeBrowserService.openBrowser(url);
                }
            }
        });
    }

    /**
     *  返回
     */
    backToProPage() {
        this.navCtrl.pop(null);
    }

    /**
     * 获取活动类型
     */
    getActivityType() {

        this.activityListPro.getActivityType(this.classify, 0)
            .subscribe((res: Array<any>) => {
                this.allTypes = res;
            }, err => {
            });
    }

    computeType(val) {
        let typeName = '';
        this.allTypes.forEach((item) => {
            if (Number(item.id) === val) {
                typeName = item.name;
            }
        });
        return typeName;
    }

    shareOut(scene) {
        let shareSmallImg = this.detailData.shareSmallImgUrl;
        this.completionUrl([shareSmallImg]).then((res) => {
            shareSmallImg = res[0];
            //分享给朋友0,分享到朋友圈1
            if (!this.shareLink) {
                this.showToast('无效的分享链接');
                return false
            }
            this.wechatService.share(scene, 'send-link-thumb-remote',
                {
                    link: this.shareLink,
                    thumb: shareSmallImg,
                    shortName: this.detailData.shortName,
                    description: this.detailData.shareDesc
                }, () => {
                    loading.dismiss();
                }
                , reason => {
                    if(reason!='用户点击取消并返回'){
                        this.showToast(`分享失败:${reason}`);
                    }
                    loading.dismiss();
                }
            );
            let loading = this.loadingCtrl.create({
                spinner: 'circles',
                content: '正在打开微信',
                dismissOnPageChange: false,
                enableBackdropDismiss: true
            });
            loading.present();
            setTimeout(() => {
                loading.dismiss();
            }, 5000);
        });

    }

    openAttachFile(resourceId: string, realFileName: string) {
        if(this.platform.is('android')) {
            this.permissionsService.checkAndroidStoragePermission().then(res => {
                if (res == 'GRANTED') {
                    this.viewAttachFile(resourceId,realFileName);
                } else if (res == 'DENIED') {
                    this.showToast('请到“设置>应用”中启用“存储”权限');
                    return;
                }
            }).catch(e => {
                console.log('检查存储权限异常',e);
            })
        } else {
            this.viewAttachFile(resourceId,realFileName);
        }
    }

    //打开附件
    viewAttachFile(resourceId: string, realFileName: string) {

        let now = 0;
        if (resourceId) {
            let loading = this.loadingCtrl.create({
                spinner: 'circles',
                content: '文件加载中: 0%',
                dismissOnPageChange: false,
                enableBackdropDismiss: true
            });
            loading.onDidDismiss(() => {
                this.fileService.abort();
            });
            loading.present();

            this.fileService.onProgress(progressEvent => {
                if (progressEvent.lengthComputable) {
                    now = progressEvent.loaded / progressEvent.total * 100;
                }
            });

            let mTimer = setInterval(() => {
                loading.setContent('文件加载中: ' + Math.floor(now) + '%');
                if (now >= 99) {
                    clearInterval(mTimer);
                }
            }, 300);

            this.fileService.getFile(resourceId, realFileName).subscribe(res => {
                    loading.dismiss();
                    // now = 0;

                    setTimeout(() => {
                        let fileUrl = res.fileUrl;
                        let mimeType = res.mimeType;
                        this.fileOpener.open(decodeURI(fileUrl), mimeType)
                            .then(() => {
                            })
                            .catch(e => {
                                if (e.message.indexOf('No Activity found to handle Intent') > -1) {
                                    if (e.message.indexOf('application/pdf') > -1) {
                                        this.showToast('请至应用商店下载安装PDF阅读器');
                                        return;
                                    } else if (e.message.indexOf('video/mp4') > -1) {
                                        this.showToast('请至应用商店下载安装MP4播放器');
                                        return;
                                    }
                                }

                                this.showToast('文件打开失败');
                            });
                    }, 300);
                },
                error2 => {
                    loading.dismiss();
                    // now = 0;
                    if (error2.code == 4 && error2.http_status == -1) {
                        this.showToast('取消加载');
                    } else {
                        this.showToast('文件加载失败，请稍后重试');
                    }

                });
        } else {
            this.showToast('文件异常');
        }


    }


    //监听到Android虚拟返回键
    private backButtonHandle = () => {
        if (this.showShareMenu) {
            this.showShareMenu = false;
            return false;
        }
        this.navCtrl.pop(null);
    };

    /**
     * 补全URL路径
     */
    completionUrl(urls) {
        return new Promise((resolve, reject) => {
            this.fileService.getAzureInfo().subscribe((res) => {
                let arr = [];
                // urls.forEach((item) => {
                //     arr.push(this.fileService.getCompletePath(item, res.azureInfo));
                // });
                let getUrl1 = this.cacheImg.getImgPath(urls[0], res.azureInfo);
                let getUrl2 = this.cacheImg.getImgPath(urls[1], res.azureInfo);
                Promise.all([getUrl1, getUrl2]).then((res) => {
                    resolve(res);
                });
            }, err => {
                reject(err);
            });
        });
    }

    switchDetail () {
        this.activity = 'detail';
    }


    detailSegmentChange(){
        const userRole = RoleFactory.getUserRole();
        if(this.activity === 'activityShare' && userRole === Role.营销员){
            const msg = '请先至中宏保险官微完成身份绑定,再进行活动转发。';
            const msgDuring = 6000;
            if(!this.showShareButton){
                this.showToast(msg,msgDuring);
                const self = this;
                setTimeout(() => {
                    self.activity = this.prevActivity;
                    self.ref.detectChanges();
                },200);
                return false;
            }
        }
        this.prevActivity = this.activity;
    }
}
